package de.klenkse.eclipse.ftpsync.synchronizer;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.net.ftp.FTPClient;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;

/**
 * Adds a new resource, e.g. uploading a file.
 */
public class ResourceAddCommand extends ResourceCommand {
	/**
	 * The resource.
	 */
	private IResource resource;
	/**
	 * The remote path.
	 */
	private String remotePath;

	/**
	 * The constructor.
	 */
	public ResourceAddCommand(IResource resource, String remoteRelPath) {
		this.resource = resource;
		this.remotePath = remoteRelPath;
	}

	/** {@inheritDoc} */
	@Override
	public String toString() {
		return "Adding " + resource.toString() + " to " + remotePath;
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @throws IOException
	 */
	@Override
	public void execute(FTPClient client) throws IOException {
		// TODO Auto-generated method stub
		if (resource instanceof IFolder) {
			client.makeDirectory(remotePath);
		} else if (resource instanceof IFile) {
			InputStream inStream;
			try {
				inStream = ((IFile) resource).getContents();
				client.storeFile(remotePath, inStream);
				inStream.close();
			} catch (CoreException e) {
				throw new IOException(e);
			}
		}
	}
}
